<template>
  <div class="min-h-screen bg-white">
    <div class="fixed top-0 left-0 w-full h-1 bg-gradient-to-r from-blue-400 via-purple-500 to-blue-600 z-50"></div>
    
    <main class="bg-gray-900 min-h-screen relative">
      <!-- 固定背景图案 -->
      <div class="absolute inset-0 overflow-hidden pointer-events-none">
        <div class="absolute h-screen w-full bg-[radial-gradient(ellipse_at_center,rgba(59,130,246,0.1),transparent_70%)] opacity-50"></div>
        <div class="absolute bottom-0 right-0 w-96 h-96 bg-blue-500/5 rounded-full blur-3xl"></div>
        <div class="absolute w-full h-px bg-gradient-to-r from-transparent via-blue-400/10 to-transparent top-[30%]"></div>
        <div class="absolute w-full h-px bg-gradient-to-r from-transparent via-blue-400/10 to-transparent bottom-[20%]"></div>
      </div>
      <div id="directory" class="max-w-7xl mx-auto px-4 pt-8 pb-16 relative z-10">
        <DirectoryGridComponent :key="refreshKey" :initial-search-query="searchQuery" />
      </div>
    </main>
    
    <footer class="bg-gray-900 text-white py-8 border-t border-gray-800">
      <div class="max-w-7xl mx-auto px-4 md:px-8">
        <div class="flex flex-col md:flex-row justify-between items-center">
          <div class="mb-4 md:mb-0 flex items-center">

            <p class="text-sm">© 2024 Agent MCP Directory. 保留所有权利。</p>
          </div>
        </div>
      </div>
    </footer>
    
    <AddProjectModalComponent 
      v-model:visible="isAddProjectModalOpen"
      @project-added="handleProjectAdded"
    />
    
    <BulkImportModalComponent 
      v-model:visible="isBulkImportModalOpen"
      @projects-added="handleProjectsAdded"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import DirectoryGridComponent from '../components/mcpAgent/DirectoryGridComponent.vue'
import AddProjectModalComponent from '../components/mcpAgent/AddProjectModalComponent.vue'
import BulkImportModalComponent from '../components/mcpAgent/BulkImportModalComponent.vue'
import { useMcpApiService } from '../services/McpApiService'
import { 
  StarFilled, 
  Money, 
  Link, 
  Message, 
  Collection, 
  RefreshRight,
  Connection
} from '@element-plus/icons-vue'

// 状态管理
const searchQuery = ref('')
const isAddProjectModalOpen = ref(false)
const isBulkImportModalOpen = ref(false)
const totalProjects = ref(100) // 默认值
const refreshKey = ref(0) // 用于强制重新渲染 DirectoryGrid
const isRefreshing = ref(false)

// 服务引用
const mcpApiService = useMcpApiService()

// 生命周期钩子
onMounted(() => {
  const lastRefresh = localStorage.getItem('lastAgentRefresh')
  const now = new Date()
  
  if (!lastRefresh || (now.getTime() - new Date(lastRefresh as string).getTime() > 24 * 60 * 60 * 1000)) {
    refreshData()
  } else {
    updateTotalProjects()
  }
})

// 方法
const refreshData = async () => {
  if (isRefreshing.value) return

  isRefreshing.value = true
  try {
    console.log('刷新代理数据...')
    const refreshedData = await mcpApiService.refreshAgentData()
    console.log(`刷新完成：找到 ${refreshedData.length} 个项目`)
    localStorage.setItem('lastAgentRefresh', new Date().toISOString())
    totalProjects.value = refreshedData.length
    refreshKey.value++ // 强制重新渲染目录
    
    ElMessage({
      message: `刷新完成：目录中共有 ${refreshedData.length} 个项目`,
      type: "success"
    })
  } catch (error) {
    console.error("刷新数据时出错:", error)
    ElMessage({
      message: "无法刷新数据。请稍后再试。",
      type: "error"
    })
    // 回退到仅计算现有项目
    updateTotalProjects()
  } finally {
    isRefreshing.value = false
  }
}

const updateTotalProjects = async () => {
  try {
    const projects = await mcpApiService.getAllProjects()
    totalProjects.value = projects.length
  } catch (error) {
    console.error("更新项目总数时出错:", error)
    ElMessage({
      message: "加载项目时出错。将显示默认数据。",
      type: "error"
    })
  }
}

const handleSearch = (query: string) => {
  searchQuery.value = query
  
  const directorySection = document.getElementById('directory')
  if (directorySection) {
    directorySection.scrollIntoView({ behavior: 'smooth' })
  }
}

const handleAddProject = () => {
  isAddProjectModalOpen.value = true
}

const handleBulkImport = () => {
  isBulkImportModalOpen.value = true
}

const handleProjectAdded = (count: number) => {
  refreshData()
  ElMessage({
    message: `已将 ${count} 个项目添加到目录。`,
    type: "success"
  })
}

const handleProjectsAdded = async (agents: any[]) => {
  try {
    console.log(`收到 ${agents.length} 个新导入的项目`)
    
    // 刷新目录数据
    await refreshData()
    
    // 显示消息通知
    ElMessage({
      message: `已将 ${agents.length} 个项目添加到目录。`,
      type: "success"
    })
    
    // 重置状态
    isBulkImportModalOpen.value = false
  } catch (error) {
    console.error("添加项目后刷新数据时出错:", error)
    ElMessage({
      message: "项目已添加，但可能需要手动刷新目录。",
      type: "warning"
    })
  }
}
</script>

<style scoped>
/* 基础样式 */
.bg-gray-900 {
  background-color: #111827;
}
.bg-gray-800 {
  background-color: #1f2937;
}
.bg-blue-500\/10 {
  background-color: rgba(59, 130, 246, 0.1);
}
.bg-blue-500\/5 {
  background-color: rgba(59, 130, 246, 0.05);
}
.text-white {
  color: #ffffff;
}
.text-white\/80 {
  color: rgba(255, 255, 255, 0.8);
}
.text-white\/70 {
  color: rgba(255, 255, 255, 0.7);
}
.text-blue-400 {
  color: #60a5fa;
}
.text-blue-300 {
  color: #93c5fd;
}
.text-gray-400 {
  color: #9ca3af;
}
.hover\:text-white:hover {
  color: #ffffff;
}
.hover\:text-blue-300:hover {
  color: #93c5fd;
}
.hover\:underline:hover {
  text-decoration: underline;
}
.backdrop-blur-sm {
  backdrop-filter: blur(4px);
}
.border-white\/10 {
  border-color: rgba(255, 255, 255, 0.1);
}
.border-white\/5 {
  border-color: rgba(255, 255, 255, 0.05);
}
.border-blue-500\/20 {
  border-color: rgba(59, 130, 246, 0.2);
}
.border-gray-800 {
  border-color: #1f2937;
}
.shadow-xl {
  box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
}

/* 功能卡片 */
.feature-card {
  padding: 1.5rem;
  border-radius: 0.75rem;
  background-color: rgba(31, 41, 55, 0.5);
  border: 1px solid rgba(255, 255, 255, 0.05);
  transition: all 0.3s ease;
}

.feature-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 10px 20px -5px rgba(0, 0, 0, 0.2);
  border-color: rgba(96, 165, 250, 0.2);
  background-color: rgba(31, 41, 55, 0.7);
}

/* 社交按钮 */
.social-button {
  display: inline-flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.5rem 1rem;
  border-radius: 0.375rem;
  background-color: rgba(31, 41, 55, 0.7);
  color: #d1d5db;
  font-weight: 500;
  transition: all 0.3s ease;
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.social-button:hover {
  background-color: rgba(31, 41, 55, 0.9);
  color: #ffffff;
}

.donate-button {
  background-color: rgba(59, 130, 246, 0.1);
  color: #60a5fa;
}

.donate-button:hover {
  background-color: rgba(59, 130, 246, 0.2);
  color: #93c5fd;
}
</style>